<template>
  <div class="page-list-live">
    <PageList>
      <template #header>员工列表</template>
      <template #filter>
        <ListFilter ref="ListFilter" :form="topFilter" :key-list="keyList" @search="handleSearch" @reset="handleReset" />
      </template>
      <template #tips>
        <el-button icon="el-icon-document-add" type="primary" class="box" @click="addHandle">自定义表头</el-button>
      </template>
      <template #table>
        <ListTable ref="RefListTable" :loading="tableLoading" :table-data="tableData" :table-col="tabList">
          <template slot="col2" slot-scope="stData">
            <div>
              <el-image
                v-if="stData.row.photo"
                style="height: 100px; width: 80px"
                :src="stData.row.photo"
                :preview-src-list="[stData.row.photo]"
              />
              <el-image
                v-else-if="stData.row.faceDetectPhoto1"
                style="height: 100px; width: 80px"
                :src="'data:image/jpg;base64,' + stData.row.faceDetectPhoto1"
                :preview-src-list="[stData.row.faceDetectPhoto1]"
              />
              <el-image
                v-else-if="stData.row.faceDetectPhoto2"
                style="height: 100px; width: 80px"
                :src="'data:image/jpg;base64,' + stData.row.faceDetectPhoto2"
                :preview-src-list="[stData.row.faceDetectPhoto2]"
              />
              <el-image
                v-else-if="stData.row.faceDetectPhoto3"
                style="height: 100px; width: 80px"
                :src="'data:image/jpg;base64,' + stData.row.faceDetectPhoto3"
                :preview-src-list="['data:image/jpg;base64,' + stData.row.faceDetectPhoto3]"
              />
              <p v-else>未上传</p>
            </div>
          </template>
          <template slot="col1" slot-scope="scope">
            <div class="btn-nav">
              <el-button
                icon="el-icon-platform-eleme"
                :loading="scope.row.loadingEdit"
                :disabled="scope.row.status === '0'"
                size="mini"
                style="margin-left: 0px; margin-right: 10px"
                type="text"
                @click="setEmployeeHandle(scope.row, scope.row.isEnable)"
              >{{ scope.row.isSystemDisable ? '启用' : '禁用' }}</el-button>
            </div>
          </template>
        </ListTable>
      </template>
    </PageList>
    <!-- 选择列表字段组件 -->
    <ListFields ref="ListFields" @setTableCol="setTableColHandler" />
  </div>
</template>
<script>
import listMixin from '@/mixins/list'
import ListFields from './ListFields'
import ListFilter from '@/components/ListFilter'
import { employee, department, job, work, setEmployee } from '@/api/api'
export default {
  components: {
    ListFilter,
    ListFields
  },
  mixins: [listMixin],
  data() {
    return {
      url: this.$imgUrl + '/Employee/ImportEmployee',
      // 部门
      dptList: [],
      // 职位
      jobList: [],
      // 工种
      workList: [],
      // 在职状态
      statusList: [],
      deleteList: {
        id: ''
      },
      // 查询字段
      topFilter: {},
      // 关键字查询
      keyList: ['employeeCode', 'name', 'rfid'],
      // 列表数据
      tableData: [],
      // 列表表头
      tableCol: [
        { prop: 'employeeCode', label: '员工编码', align: 'center', minWidth: '120px' },
        { prop: 'name', label: '员工姓名', align: 'center', minWidth: '80px' },
        {
          prop: 'sex',
          label: '性别',
          align: 'center',
          minWidth: '54px',
          formatter(row, col, cell) {
            let sex
            const sexList = [
              { label: '男', value: 1 },
              { label: '女', value: 0 }
            ]
            sexList.forEach((item) => {
              if (item.value === cell) {
                sex = item.label
              }
            })
            return sex
          }
        },
        {
          prop: 'birthday',
          label: '生日',
          align: 'center',
          minWidth: '96px',
          formatter(row, col, cell) {
            const date = new Date(cell)
            const year = date.getFullYear()
            let month = date.getMonth() + 1
            month = month >= 10 ? month : '0' + month
            let d1 = date.getDate()
            d1 = d1 >= 10 ? d1 : '0' + d1
            const time_str = year + '-' + month + '-' + d1
            return cell ? time_str : '--'
          }
        },
        { prop: 'idCard', label: '身份证号', align: 'center', minWidth: '166px' },
        { prop: 'phone', label: '手机号', align: 'center', minWidth: '110px' },
        { prop: 'email', label: '邮箱', align: 'center', minWidth: '180px' },
        { prop: 'adress', label: '地址', align: 'center', minWidth: '200px' },
        {
          prop: 'photo',
          label: '照片',
          custom: 'col2',
          minWidth: '100px',
          align: 'center'
        },
        {
          prop: 'departmentId',
          label: '部门',
          minWidth: '80px',
          align: 'center',
          formatter(row, col, cell) {
            return row.department ? row.department.deptName : '--'
          }
        },
        {
          prop: 'jobId',
          label: '职位',
          minWidth: '80px',
          formatter(row, col, cell) {
            return row.job ? row.job.jobTitle : '--'
          },
          align: 'center'
        },
        {
          prop: 'workId',
          label: '工种',
          minWidth: '80px',
          formatter(row, col, cell) {
            return row.work ? row.work.workName : '--'
          },
          align: 'center'
        },
        { prop: 'rfid', label: 'RFID卡', minWidth: '80px', align: 'center' },
        { prop: 'accessCardID', label: '门禁ID', minWidth: '80px', align: 'center' },
        {
          prop: 'status',
          label: '工作状态',
          minWidth: '80px',
          formatter(row, col, cell) {
            return row.status === '1' ? '在职' : row.status === '0' ? '离职' : row.status
          },
          align: 'center'
        },
        {
          prop: 'faceDetect',
          label: '人脸识别',
          minWidth: '80px',
          formatter(row, col, cell) {
            return row.faceDetect === 1 ? '启用' : '禁用'
          },
          align: 'center'
        },
        {
          prop: 'isEnable',
          label: '门禁启用/禁用',
          minWidth: '118px',
          formatter(row, col, cell) {
            return row.isEnable ? '启用' : '禁用'
          },
          align: 'center'
        },
        { prop: 'comment', label: '备注', align: 'center', minWidth: '180px' },
        { label: '操作', custom: 'col1', align: 'center', minWidth: '108px' }
      ],
      tabList: [],
      tableColValue: [],
      // 启用禁用
      isEnableSwitch: false
    }
  },
  mounted() {
    // 获取下拉框数据并赋值给查询组件
    this.threeList()
    const listTable = localStorage.getItem('listTabel')
    if (!listTable) {
      this.tabList = this.tableCol
      return
    }
    this.tabList = []
    this.tableColValue = JSON.parse(listTable)
    this.tableColValue.forEach((item) => {
      this.tableCol.forEach((edit) => {
        if (item.label === edit.label) {
          this.tabList.push(edit)
        }
      })
    })
  },
  methods: {
    // 启用禁用门禁
    async setEmployeeHandle(value, flag) {
      let font = ''
      if (flag) {
        font = '禁用后，当前员工将无法通过人员闸机通道，是否禁用？'
      } else {
        font = '启用后，当前员工将可以通过人员闸机通道，是否启用？'
      }
      this.$confirm(font, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            const res = await setEmployee('POST', {
              employeeId: value.id,
              isEnable: !value.isEnable
            })
            if (res.code !== 200) {
              return
            }
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.getList(this.serchObj)
          } catch (err) {
            this.$message.error('操作失败！')
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
    },
    // 设置表头
    setTableColHandler(value) {
      this.tabList = []
      this.tabList = [...value]

      this.tableColValue = value
      localStorage.setItem('listTabel', JSON.stringify(this.tableColValue))
    },
    // 选择表单字段
    addHandle() {
      this.$refs.ListFields.open()
      this.$refs.ListFields.selectionChange(this.tableColValue)
    },
    // 部门
    async dptHandler() {
      try {
        const obj = { pageIndex: 1, pageSize: 1e8 }
        const res = await department('post', obj, false)
        if (res.code === 200) {
          this.dptList = [
            {
              label: '空',
              value: '空'
            }
          ]
          // this.dptList = []
          res.data.items.map((item) => {
            this.dptList.push({
              label: item.deptName,
              value: item.id
            })
          })
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 职位
    async jobHandler() {
      try {
        const obj = { pageIndex: 1, pageSize: 1e8 }
        const res = await job('post', obj, false)
        if (res.code === 200) {
          this.jobList = [
            {
              label: '空',
              value: '空'
            }
          ]
          // this.jobList = []
          res.data.items.map((item) => {
            this.jobList.push({
              label: item.jobTitle,
              value: item.id,
              department: item.department
            })
          })
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 工种
    async workHandler() {
      try {
        const obj = { pageIndex: 1, pageSize: 1e8 }
        const res = await work('post', obj, false)
        if (res.code === 200) {
          this.workList = [
            {
              label: '空',
              value: '空'
            }
          ]
          // this.workList = []
          res.data.items.map((item) => {
            this.workList.push({
              label: item.workName,
              value: item.id
            })
          })
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 查询部门，职位，工种
    async threeList() {
      await this.jobHandler()
      await this.dptHandler()
      await this.workHandler()
      this.$nextTick(() => {
        this.topFilter = {
          departmentId: {
            label: '部门',
            placeholder: '请选择员工部门',
            type: 'select',
            arr: this.dptList
          },
          jobId: {
            label: '职位',
            placeholder: '请选择员工职位',
            type: 'select',
            arr: this.jobList
          },
          workId: {
            label: '工种',
            placeholder: '请选择员工工种',
            type: 'select',
            arr: this.workList
          },
          status: {
            label: '工作状态',
            placeholder: '请选择工作状态',
            type: 'select',
            arr: [
              { label: '在职', value: '1' },
              { label: '离职', value: '0' }
            ]
          },
          keyword: {
            label: '关键字',
            placeholder: '请输入员工编码或姓名、RFID、门禁ID'
          }
        }
      })
    },
    // 请求列表数据
    async getList(query) {
      this.tableLoading = true
      try {
        const obj = query || { pageIndex: 1, pageSize: 10, orderBy: 'name', orderByAscent: false }
        obj.orderBy = 'name'
        const {
          data: { items: resData, count, pageIndex }
        } = await employee('post', obj, false)
        this.tableData = resData.map((item) => {
          item.loadingEdit = false
          item.loadingDel = false
          return item
        })
        this.$nextTick(() => {
          this.$refs['RefListTable'].update({ page: pageIndex, count })
          this.tableLoading = false
        })
      } catch (err) {
        this.tableLoading = false
      }
    },
    afterEditSuccess() {
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
  .el-button:focus,
  .el-button:focus:hover {
    color: #586aa6 !important;
  }
  .box:focus:hover {
    color: #fff !important;
  }
</style>
